//
//  TSProfitFooterView.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/15.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

protocol TSProfitFooterViewDelegate : NSObjectProtocol {
    
    func didClickRecord()
    func completeInvest(_ args : (Array<String>, String, String))
}

class TSProfitFooterView: UIView {
    
    weak var delegate : TSProfitFooterViewDelegate?
    private var dataSource : [TSResultModel] = []
    private var rankDataSource : [TSResultModel] = []
    private var randomArray : [String] = []
    private var collectionView : UICollectionView!
    private var rankCollectionView : UICollectionView!
    private var inputField : UITextField!
    private var selectRankModel : TSResultModel? = nil
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = WHITE_COLOR
        configViews()
    }
    
    func resetState() {
        
        resetAction()
        
        self.inputField.text = "1";
    }
    
    @objc private func tapGesture(gesture:UITapGestureRecognizer) {
        
        let recordVc = TSAccountRecordViewController()
        recordVc.recordType = TSRecordType.investType
        
        if self.delegate != nil {
            self.delegate?.didClickRecord()
        }
//        UIViewController.currentViewController().navigationController?.pushViewController(recordVc, animated: true)
    }
    
    @objc private func commitAction() {

        let times = inputField.text
        var numArray : Array<String> = []
        
        for model in dataSource {
            if model.isSelected {
                numArray.append(model.title)
            }
        }
        
        if times?.count ?? 0 > 0 && isPurnInt(string: times!) {
            
            guard numArray.count == 3 else {
                CBToast.showToastAction(message: "请最少选择3个号码")
                return
            }
            
            guard self.selectRankModel != nil else {
                CBToast.showToastAction(message: "请选择名称")
                return
            }
            
            if self.delegate != nil {
                self.delegate?.completeInvest((numArray, times!, getCurrentRank(rank: self.selectRankModel!.title)))
            }
//            TSLog(numArray)
//            TSLog(times!)
//            TSLog(self.selectRankModel!.title)
            
        } else {
            CBToast.showToastAction(message: "请输入投注的倍数")
        }
    }
    
    @objc private func randomAction() {
        
        resetAction()
        
        randomArray.removeAll()
        createRandomResult()
        createRankRandom()
        
    }
    
    @objc private func resetAction() {
        
        for item in dataSource {
            item.isSelected = false
        }
        for index in 0..<rankDataSource.count {
            let model = rankDataSource[index]
            model.isSelected = index == 0
            if index == 0 {
                self.selectRankModel = model
            }
        }
        
        collectionView.reloadData()
        rankCollectionView.reloadData()
    }
    
    private func createRandomResult() {
        
        for _ in 0..<3 {
            createRandomNumber()
        }
        
        for str in randomArray {
            
            for index in 0..<dataSource.count {
                let model = dataSource[index]
                if str == model.title {
                    model.isSelected = true
                    dataSource[index] = model
                    break
                }
            }
        }
        collectionView.reloadData()
        
        TSLog(randomArray)
    }
    
    private func createRandomNumber() {
        
        let number = arc4random() % 10 + 1
        if randomArray.contains("\(number)") {
            createRandomNumber()
        } else {
            randomArray.append("\(number)")
        }
    }
    
    private func createRankRandom() {
        
        let number = arc4random() % 11
        self.selectRankModel = nil
        for index in 0..<self.rankDataSource.count {
            let model = self.rankDataSource[index]
            model.isSelected = number == index
            if model.isSelected {
                self.selectRankModel = model
            }
        }
        self.rankCollectionView.reloadData()
    }
    
    @objc private func decreaseAction() {
        
        if inputField.text?.count == 0 {
            return
        }
        
        var count = Int(inputField.text!)!
        if count == 1 {
            return
        }
        
        count -= 1
        inputField.text = "\(count)"
    }
    
    @objc private func increaseAction() {
        
        if inputField.text?.count == 0 {
            return
        }
        
        var count = Int(inputField.text!)!
        
        count += 1
        inputField.text = "\(count)"
    }
    
    // 判断输入的字符串是否为数字，不含其它字符
    func isPurnInt(string: String) -> Bool {

        let scan: Scanner = Scanner(string: string)
        var val:Int = 0
        return scan.scanInt(&val) && scan.isAtEnd

     }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension TSProfitFooterView : UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if collectionView == self.collectionView {
            
            let model = dataSource[indexPath.item]
                    
                    if !model.isSelected {
                        
                        var count = 0
                        for model in dataSource {
                            if model.isSelected {
                                count += 1
                            }
                        }
                        
                        guard count < 3 else {
                            CBToast.showToastAction(message: "最多只能选择4个号码")
                            return
                        }
                    }
                
                    model.isSelected = !model.isSelected
            //        dataSource[indexPath.item] = model
            
        } else {
            
            for item in rankDataSource {
                item.isSelected = false
            }
            let model = rankDataSource[indexPath.item]
            model.isSelected = true
            self.selectRankModel = model
            
        }
        
        collectionView.reloadData()
    }
    
}

extension TSProfitFooterView : UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionView == self.collectionView ? dataSource.count : rankDataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(TSResultCollectionViewCell.self), for: indexPath) as? TSResultCollectionViewCell
        
        if collectionView == self.collectionView {
            cell?.setupCell(model: dataSource[indexPath.item])
        } else {
            cell?.setupCell(model: rankDataSource[indexPath.item])
        }
        
        return cell!
    }
}

extension TSProfitFooterView {
    
    private func configViews() {
        
        for i in 1..<11 {
            let model = TSResultModel.init()
            model.title = String.init(format: "%d", i)
            model.isSelected = false
//            let model = TSResultModel.init(title: i, isSelected: false)
            dataSource.append(model)
        }
        
        let array = ["冠军", "亚军", "季军", "四名", "五名", "六名", "七名", "八名", "九名", "十名"]
        for index in 0..<array.count {
            let model = TSResultModel.init()
            model.title = array[index]
            model.isSelected = index == 0
            if index == 0 {
                self.selectRankModel = model
            }
            rankDataSource.append(model)
        }
        
        let view = UIView.init()
        view.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        addSubview(view)
        view.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(10)
        }
        
        let topContainer = UIView.init()
        topContainer.backgroundColor = WHITE_COLOR
        topContainer.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(tapGesture(gesture:))))
        addSubview(topContainer)
        topContainer.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.snp.bottom)
            make.height.equalTo(30)
        }
        
        let line = UIView.init()
        line.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#E6E6E6")
        topContainer.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        
        let titleLabel = UILabel.init()
        titleLabel.text = "冠军"
        titleLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        titleLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        topContainer.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(15)
        }
        
        let icon = UIImageView.init(image: UIImage(named: "general_more"))
        topContainer.addSubview(icon)
        icon.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().inset(15)
            make.size.equalTo(CGSize(width: 8, height: 14))
        }
        
        let recordLabel = UILabel.init()
        recordLabel.text = "投注记录"
        recordLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        recordLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        topContainer.addSubview(recordLabel)
        recordLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalTo(icon.snp.left).offset(-5)
        }
        
        let selectLabel = UILabel.init()
        selectLabel.text = "请选择号码"
        selectLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        selectLabel.font = UIFont.systemFont(ofSize: 16)
        addSubview(selectLabel)
        selectLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(topContainer.snp.bottom).offset(20)
        }
        
        let itemW : CGFloat = 30
        let collectionW = CGFloat(SCREEN_WIDTH * 0.87)
        let margin = (collectionW - 5 * itemW) / 4 - 10
        
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = CGSize(width: 30, height: 30)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = 10
        
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = WHITE_COLOR
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.bounces = false
        collectionView.register(TSResultCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(TSResultCollectionViewCell.self))
        addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview().inset(25)
            make.top.equalTo(selectLabel.snp.bottom).offset(20)
            make.height.equalTo(70)
        }
        
        let rankLabel = UILabel.init()
        rankLabel.text = "请选择名次"
        rankLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        rankLabel.font = UIFont.systemFont(ofSize: 16)
        addSubview(rankLabel)
        rankLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(collectionView.snp.bottom).offset(20)
        }
        
        let rankLayout = UICollectionViewFlowLayout.init()
        rankLayout.itemSize = CGSize(width: 30, height: 30)
        rankLayout.minimumInteritemSpacing = margin
        rankLayout.minimumLineSpacing = 10
        
        rankCollectionView = UICollectionView.init(frame: .zero, collectionViewLayout: rankLayout)
        rankCollectionView.backgroundColor = WHITE_COLOR
        rankCollectionView.delegate = self
        rankCollectionView.dataSource = self
        rankCollectionView.bounces = false
        rankCollectionView.register(TSResultCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(TSResultCollectionViewCell.self))
        addSubview(rankCollectionView)
        rankCollectionView.snp.makeConstraints { (make) in
            make.left.right.equalTo(collectionView)
            make.top.equalTo(rankLabel.snp.bottom).offset(20)
            make.height.equalTo(collectionView)
        }
        
        let bottomContainer = UIView.init()
        bottomContainer.backgroundColor = WHITE_COLOR
        addSubview(bottomContainer)
        bottomContainer.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(rankCollectionView.snp.bottom).offset(20)
            make.height.equalTo(18)
        }
        
        let unitLabel = UILabel.init()
        unitLabel.text = "元"
        unitLabel.textAlignment = .center
        unitLabel.textColor = WHITE_COLOR
        unitLabel.backgroundColor = BASE_RED_COLOR
        unitLabel.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        unitLabel.layer.cornerRadius = 2
        unitLabel.layer.masksToBounds = true
        bottomContainer.addSubview(unitLabel)
        unitLabel.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.top.equalToSuperview()
            make.size.equalTo(CGSize(width: 15, height: 15))
        }
        
        let modelLabel = UILabel.init()
        modelLabel.text = "模式"
        modelLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#323232")
        modelLabel.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        bottomContainer.addSubview(modelLabel)
        modelLabel.snp.makeConstraints { (make) in
            make.left.equalTo(unitLabel.snp.right).offset(5)
            make.centerY.equalTo(unitLabel)
        }
        
        let randomBtn = UIButton.init(type: .system)
        randomBtn.setTitle("机选", for: .normal)
        randomBtn.setTitleColor(WHITE_COLOR, for: .normal)
        randomBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        randomBtn.backgroundColor = BASE_RED_COLOR
        randomBtn.layer.cornerRadius = 9
        randomBtn.layer.masksToBounds = true
        randomBtn.addTarget(self, action: #selector(randomAction), for: .touchUpInside)
        bottomContainer.addSubview(randomBtn)
        randomBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(unitLabel)
            make.right.equalToSuperview().inset(15)
            make.size.equalTo(CGSize(width: 38, height: 18))
        }
        
        let resetBtn = UIButton.init(type: .system)
        resetBtn.setTitle("清空", for: .normal)
        resetBtn.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#646464"), for: .normal)
        resetBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        resetBtn.backgroundColor = WHITE_COLOR
        resetBtn.layer.cornerRadius = 9
        resetBtn.layer.masksToBounds = true
        resetBtn.layer.borderColor = UIColor.hexadecimalColor(hexadecimal: "#B4B4B4").cgColor
        resetBtn.layer.borderWidth = 1
        resetBtn.addTarget(self, action: #selector(resetAction), for: .touchUpInside)
        bottomContainer.addSubview(resetBtn)
        resetBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(unitLabel)
            make.right.equalTo(randomBtn.snp.left).offset(-10)
            make.size.equalTo(randomBtn)
        }
        
        let countLabel = UILabel.init()
        countLabel.text = "倍数："
        countLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        countLabel.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        bottomContainer.addSubview(countLabel)
        countLabel.snp.makeConstraints { (make) in
            make.left.equalTo(modelLabel.snp.right).offset(25)
            make.centerY.equalTo(unitLabel)
        }
        
        let decreaseBtn = UIButton.init(type: .system)
        decreaseBtn.setBackgroundImage(UIImage(named: "main_invest_reduce"), for: .normal)
//        decreaseBtn.setTitle("-", for: .normal)
//        decreaseBtn.setTitleColor(WHITE_COLOR, for: .normal)
//        decreaseBtn.backgroundColor = BASE_PURPLE_COLOR
//        decreaseBtn.layer.cornerRadius = 8
//        decreaseBtn.layer.masksToBounds = true
        decreaseBtn.addTarget(self, action: #selector(decreaseAction), for: .touchUpInside)
        bottomContainer.addSubview(decreaseBtn)
        decreaseBtn.snp.makeConstraints { (make) in
            make.left.equalTo(countLabel.snp.right).offset(5)
            make.centerY.equalTo(unitLabel)
            make.size.equalTo(CGSize(width: 16, height: 16))
        }
        
        inputField = UITextField.init()
        inputField.text = "1"
        inputField.keyboardType = .decimalPad
        inputField.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        inputField.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        inputField.textAlignment = .center
        inputField.borderStyle = .roundedRect
        bottomContainer.addSubview(inputField)
        inputField.snp.makeConstraints { (make) in
            make.centerY.equalTo(decreaseBtn)
            make.left.equalTo(decreaseBtn.snp.right).offset(5)
            make.size.equalTo(CGSize(width: 38, height: 24))
        }
        
        let increaseBtn = UIButton.init(type: .system)
        increaseBtn.setBackgroundImage(UIImage(named: "main_invest_add"), for: .normal)
//        increaseBtn.setTitle("+", for: .normal)
//        increaseBtn.setTitleColor(WHITE_COLOR, for: .normal)
//        increaseBtn.backgroundColor = BASE_PURPLE_COLOR
//        increaseBtn.layer.cornerRadius = 8
//        increaseBtn.layer.masksToBounds = true
        increaseBtn.addTarget(self, action: #selector(increaseAction), for: .touchUpInside)
        bottomContainer.addSubview(increaseBtn)
        increaseBtn.snp.makeConstraints { (make) in
            make.left.equalTo(inputField.snp.right).offset(5)
            make.centerY.equalTo(unitLabel)
            make.size.equalTo(decreaseBtn)
        }
    
        let footerView = UIView.init()
        footerView.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        addSubview(footerView)
        footerView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(bottomContainer.snp.bottom).offset(10)
            make.height.equalTo(90)
        }
        
        let commitBtn = UIButton.init(type: .system)
        commitBtn.setTitle("确认投注", for: .normal)
        commitBtn.setTitleColor(WHITE_COLOR, for: .normal)
        commitBtn.backgroundColor = BASE_RED_COLOR
        commitBtn.layer.cornerRadius = 24
        commitBtn.layer.masksToBounds = true
        commitBtn.addTarget(self, action: #selector(commitAction), for: .touchUpInside)
        footerView.addSubview(commitBtn)
        commitBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(20)
            make.size.equalTo(CGSize(width: SCREEN_WIDTH*0.682, height: 48))
        }
    }
    
    func getCurrentRank(rank:String) -> String {
        
        switch rank {
        case "冠军":
            return "one"
        
        case "亚军":
            return "two"
        
        case "季军":
            return "three"
        
        case "四名":
            return "four"
        
        case "五名":
            return "five"
        
        case "六名":
            return "six"
        
        case "七名":
            return "seven"

        case "八名":
            return "eight"
        
        case "九名":
            return "nine"
        
        case "十名":
            return "ten"
        default:
            return "one"
        }
    }
}
